package com.lxy.labsystem.controller;

import com.lxy.labsystem.pojo.User;
import com.lxy.labsystem.service.UserService;
import com.lxy.labsystem.utils.ResultOBJ;
import com.lxy.labsystem.utils.SYSConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/adminapi/users")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping
    public List<User>getUserList(User user){
        return userService.getUserList(user);
    }

    @PostMapping("/login")
    public ResultOBJ login(@RequestBody User user){
        try{
            List<User> list = userService.getUserList(user);
            if(list.isEmpty()) {
                throw new RuntimeException();
            }
            return new ResultOBJ(SYSConstant.CODE_SUCCESS,SYSConstant.LOGIN_SUCCESS,list.get(0));
        } catch (Exception e){
            return new ResultOBJ(SYSConstant.CODE_ERROR,SYSConstant.LOGIN_ERROR);
        }

    }

    @PostMapping
    public ResultOBJ addUserList(@RequestBody User user){
        try{
            userService.addUserList(user);
            return ResultOBJ.ADD_SUCCESS;
        } catch (Exception e){
            //throw new RuntimeException(e);
            return ResultOBJ.ADD_ERROR;
        }
    }

    @PutMapping(value="/{id}")
    public ResultOBJ updateUserList(@PathVariable Integer id ,@RequestBody User user){
        try{
            user.setId(id);
            userService.updateUserList(user);
            return ResultOBJ.UPDATE_SUCCESS;
        }catch (Exception e){
            return ResultOBJ.UPDATE_ERROR;
        }
    }

    @DeleteMapping(value="/{id}")
    public ResultOBJ deleteUserList(@PathVariable Integer id){
        try{
            userService.deleteUserList(id);
            return ResultOBJ.DELETE_SUCCESS;
        }catch (Exception e){
            return ResultOBJ.DELETE_ERROR;
        }
    }
}
